package study.io.springboot.upload.controller;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.http.HttpUtil;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import study.eggs.result.Result;
import study.eggs.result.Results;

import java.io.File;
import java.io.FileOutputStream;

@Slf4j
@RestController
@RequestMapping("/download")
public class _2_DownloadController {

    /**
     * 流读入内存
     */
    @RequestMapping("/toMemory")
    public Result toMemory(@RequestBody Request request) {
        //
        byte[] data;
        try {
            //
            data = HttpUtil.downloadBytes(request.getUrl());
            log.info(">>>>> {}", data.length);


        } finally {
            //
            data = new byte[0];
        }
        return Results.ok();
    }

    /**
     * 流保存为本地文件
     * 1.流使用完需要关闭，否则跟流关联文件不可删除
     */
    @RequestMapping("/toFile")
    public Result toFile(@RequestBody Request request) {
        //创建临时文件
        File tempFile = FileUtil.newFile(IdUtil.fastSimpleUUID());
        try (FileOutputStream fos = new FileOutputStream(tempFile)) {
            //
            Long size = HttpUtil.download(request.getUrl(), fos, false);
            log.info(">>>>> {}", size);

            //
        } catch (Exception ex) {
            throw new RuntimeException("", ex);
        } finally {
            //删除临时文件
            FileUtil.del(tempFile);
        }
        return Results.ok();
    }


    @Data
    public class Request {
        private String url;
        private String dest;
    }
}
